package com.kin207.netty.session;

import java.util.HashMap;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.context.RequestContext;

import io.netty.channel.ChannelHandlerContext;

public class SessionManager extends SessionManagerAbs {
	final static Logger logger = LoggerFactory.getLogger(SessionManager.class);
	
	private static SessionManager instance;
	
	public static synchronized SessionManager newInstance(){
		if(instance==null){
			instance = new SessionManager();
		}
		return instance;
	}
	
	public void setMessageEnd(String messageEnd){
		this.messageEnd = messageEnd;
	}
	
	public String getMessageEnd(){
		return this.messageEnd;
	}
	public int sendMessage(ChannelHandlerContext ctx, String msg,long time){
		int result = 1;
		logger.debug("send message, address:{}, message:{}", ctx.channel().remoteAddress(), msg);
		try {
			ctx.writeAndFlush(msg);
			result = 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public int sendMessage(String cid,String msg,long time){
		Session session = sessions.get(cid);
		if(session==null){
			logger.debug("send message, session {} is non-existent.", cid);
			return 1;
		}
		logger.debug("send message, session:{} is time  message:{} cid ", time,cid);
		int result = sendMessage(session.getChannelHandlerContext(), msg,time);
		return result;
	}
	public int sendMessageForName(String clientName,String msg,long time){
		String cid = names.get(clientName);
		if(cid==null){
			logger.debug("send message, name {} is non-existent.", cid);
			return 1;
		}
		logger.debug("send CID is .", cid);
		return sendMessage(cid, msg,time);
	}
	public int sendGroupMessage(String groupName, String msg,long time){
		Set<String> group = groups.get(groupName);
		if(group==null){
			logger.debug("send group message, gorup {} is non-existent.", groupName);
			return 1;
		}
		
		for(String cid : group){
			sendMessage(cid, msg,time);
		}
		
		return 0;
	}
	public int sendSystemMessage(String msg,long time){
		logger.debug("send system message.");
		for(Session item : sessions.values()){
			sendMessage(item.getChannelHandlerContext(), msg, time);
		}
		return 0;
	}



}
